#!/bin/bash

force=0

format(){
    echo "$1                $2"
}

usage(){
    echo "Usage:"
    format "-h,--help" "获得帮助"
    format "-f" "重新安装"
    echo "使用："
    echo "  仅仅获取证书"
    echo "  sudo certbot --nginx"
    echo "  指定nginx安装目录,会修改指定目录下的配置文件"
    echo "  certbot certonly --nginx --nginx-server-root=/root/nginx/conf"
    echo "  自动续订"
    echo "  certbot renew --dry-run"
    echo "  使用定时任务："
    echo "  01 * 01 * * certbot renew --dry-run"
    echo "官方网站:"
    echo "  https://letsencrypt.org/"
    echo "  https://certbot.eff.org/"
    echo "支持系统:"
    echo "  debian9、10"
    echo "  cetntos7、8"
}

set -- $(getopt -q -o "hi" -l help,install -- "$@")

while [ -n $1 ]
do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        -f)
            force=1
            ;;
        *)
            break
            ;;    
    esac
done

which certbot > /dev/null 2>&1
if [[ $? -eq 0 && $force -eq 0 ]]
then
    echo 'certbot已经安装，你可以使用-f参数重新安装'
    exit 0
fi

installSnapd(){
    # debian 9、10
    which apt > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo apt update > /dev/null 2>&1
        sudo apt install -y snapd
        sudo snap install core
        return 0
    fi
    # centos8~
    which dnf > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo dnf install -y epel-release > /dev/null 2>&1
        sudo dnf upgrade > /dev/null 2>&1
        sudo dnf install -y snapd
        sudo systemctl enable --now snapd.socket
        sudo ln -s /var/lib/snapd/snap /snap 
        return 0
    fi

    # centos7~
    which yum > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo yum install -y epel-release > /dev/null 2>&1
        sudo yum install -y snapd
        sudo systemctl enable --now snapd.socket
        sudo ln -s /var/lib/snapd/snap /snap 
        return 0
    fi

    return 1
}

if [ ! -d /var/lib/snapd ]
then
    echo "Install Snapd:"
    installSnapd
fi

installCertbot(){

    which apt-get > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo snap install core
        sudo snap refresh core
        sudo apt-get remove -y certbot
        sudo snap install --classic certbot
        sudo ln -s /snap/bin/certbot /usr/bin/certbot
        return 0
    fi

    which yum > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo snap install core
        sudo snap refresh core
        sudo yum remove -y certbot > /dev/null 2>&1
        sudo snap install --classic certbot
        sudo ln -s /snap/bin/certbot /usr/bin/certbot
        return 0
    fi

    which dnf > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        sudo snap install core
        sudo snap refresh core
        sudo dnf remove certbot > /dev/null 2>&1
        sudo snap install --classic certbot
        sudo ln -s /snap/bin/certbot /usr/bin/certbot
        return 0
    fi

    return 1
}

echo "Install Certbot:"
installCertbot